import '../public/index'
import url from '../data/url'
import request from '../data/request'
import { header, aliyun } from '../data/config'
import store from 'store'
import { getUrlParam, random_string, get_suffix, previewImg, imgPreviewModal } from '../data/util'

import {
  contacts as valid_name,
  price as valid_price,
  checkManagerNo as valid_checkManagerNo,
  checkImg as valid_checkImg
} from '../data/validate'

const base                      = url.base,
      getBuildingDetail         = request.getBuildingDetail,
      addOrModifyBuildinginfo   = request.addOrModifyBuildinginfo,
      getProvinceList           = request.getProvinceList,
      getCityList               = request.getCityList,
      getDeveloperList          = request.getDeveloperList,
      getPaychannelList         = request.getPaychannelList,
      getBank                   = request.getBank,
      getServiceType            = request.getServiceType,
      resetAdminNo              = request.resetAdminNo,
      getInformBookTemplateList = request.getInformBookTemplateList;

// 页面标题
const title  = '楼盘',
      action = '修改'

let form = new Vue({
  el: '#form',
  data: () => ({
    id: '',
    propertyName: '',
    dId: '',
    developerName: '',
    developerList: [],
    province: '',
    provinceList: [],
    city: '',
    cityList: [],
    serviceType: '',
    serviceTypeList: [],
    // otherServiceType: [],
    otherServiceTypeList: [],
    propertyAddress: '',
    picName: '',
    picMobile: '',
    channel: [],
    channelList: [],
    isView: 0,
    // isQuickLock: 0,
    lockImg: '',
    islockImgLock: false,
    // 锁屏图片上传进度
    lockImgProgress: 0,
    lockImgPreview: '',
    // 超时锁定时间 默认15分钟
    // lockTime: 15,
    // 超时锁定时间选择项 1-15 分钟
    lockTimeList: Array.apply(null, Array(15)).map((i, _i) => (_i + 1)),
    broker: 0,
    // posSignature: 0,
    // isShowName: 0,
    // showBankInfo: 1,
    // isCheckZxbg           : 0,
    // isPayToDev            : 0,
    isCreateTestType: 0,
    changePosPay: 0,
    brokerCommModel: 1,
    brokerCommConfig: '',
    careerCounselorModel: 1,
    careerCounselorConfig: '',
    propertyArea: '',
    propertyAreaList: [{
      code: 'hd',
      name: '华东'
    }, {
      code: 'hx',
      name: '华西'
    }, {
      code: 'hn',
      name: '华南'
    }, {
      code: 'hb',
      name: '华北'
    }, {
      code: 'hz',
      name: '华中'
    }],
    salePhone: '',
    longitude: '',
    latitude: '',
    openQuotationTime: '',
    // templetId: '',
    templetIdList: [],
    // printNum: 1,
    // printNumList: [1, 2],
    // ylTicketCount: 2,
    // ylTicketCountList: [1, 2],
    isLock: true,
    isMap: false,
    // 是否签名
    // isSignature: 0,
    cancelDeposit: 0,
    // refundReceiveSMSPhone: '',
    rootBank: '',
    rootBankList: [],
    defautBankCode: '',
    defautBankCodeList: [],
    // orderOverdueTime: '',
    // overdueTime: '',
    agreement: 0,
    isReset: false,
    adminNo: '',
    adminName: '',
    adminPhone: ''
  }),
  mounted: function () {

    let that = this,
        id   = getUrlParam('id');

    if (!id) {
      layer.msg('未获取到id,将跳转到列表页', {
        icon: 5
      })

      setTimeout(() => {
        window.location = './index.html'
      }, 1000)

      return
    }

    let loading = layer.msg('初始化数据中...', {
      icon: 16,
      time: 0,
      shade: .5
    });

    this.id = id;
    this.initMap();
    this.initTime();

    Promise
      .all([this.getBuildingDetail(), this.getProvinceList(), this.getDeveloper(), this.getPaychannelList(), this.getServiceTypeList(), this.getInformBookTemplateList(), this.getHeadBankList()])
      .then((res) => {

        const detailData = res[0].object
        // 合并数据
        $.extend(that.$data, detailData, {
          isReset: detailData.adminNo !== '',
          isLock: false,
          channel: detailData.chanelId ? detailData.chanelId.split(',') : [],
          rootBank: detailData.chanelId,
          lockImgPreview: detailData.lockImg ? previewImg(detailData.lockImg, { 'process': 'image/resize,w_350' }) : '',
        })

        layer.close(loading);
        that.isLock = false;

        that.provinceList    = res[1].object;
        that.developerList   = res[2].object;
        that.channelList     = res[3].object;
        that.serviceTypeList = res[4].object;
        that.templetIdList   = res[5].object;
        that.rootBankList    = res[6].object;

        that.getBranchBankList(that.rootBank);

        that.getOtherServiceTypeList(that.serviceType);

        that.otherServiceType = (res[0].object.otherServiceTypeCN).split(',');
      })
      .catch((error) => {
        console.log(error)

        layer.close(loading)
        layer.msg(error || '初始化数据失败！', {
          icon: 5
        })
      })

    valid()
  },
  watch: {
    agreement: function (val) {
      console.log('agreement====>>>', val)
    },
    province: function (val, oldVal) {
      this.getCityList(val, _.findIndex(this.provinceList, (item) => (item.id.toString() === this.province.toString())))
    },
    cityList: function (val, oldVal) {

      // 初始化时显示用户之前填写的数据
      if (!this.isInit) {
        this.city   = store.get('storeData').city;
        this.isInit = true;

        return
      }
      // 默认显示第一条数据
      if (val.length) {
        this.city = val[0].id
      }
    }
  },
  methods: {
    // 获取楼盘详情
    getBuildingDetail: () => (
      new Promise((resolve, reject) => {

        $.ajax({
          url: base + getBuildingDetail,
          type: 'post',
          headers: header,
          data: {
            id: getUrlParam('id')
          }
        })
          .done(function (res) {
            if (res.code === 0) {
              resolve(res)
            }
            reject(res.message)
          })
          .fail(function () {
            reject()
          })
          .always(function () {
          })

      })
    ),
    // 获取省列表
    getProvinceList: () => (
      new Promise((resolve, reject) => {

        $.ajax({
          url: base + getProvinceList,
          headers: header
        })
          .done(function (res) {
            if (res.code === 0) {
              resolve(res)
            }
            reject(res.message)
          })
          .fail(function () {
            reject()
          })
          .always(function () {
          })

      })
    ),
    // 获取城市列表
    getCityList: function (id, index) {
      let that = this

      // 检测index有效性
      if (!(/^\d+$/.test(index)) && index < 0) {
        return
      }

      // 如果已请求过数据则直接读取缓存的数据
      if (this.provinceList[index].cityList) {
        that.cityList = this.provinceList[index].cityList
        return
      }

      let loading = layer.msg('获取数据中...', {
        icon: 16,
        time: 0
      })

      $.ajax({
        url: base + getCityList,
        headers: header,
        data: {
          provinceId: id || 1
        }
      })
        .done(function (res) {
          if (res.code === 0) {
            // 缓存数据到省市列表里
            that.cityList = that.provinceList[index].cityList = res.object
            return
          }

          layer.msg('初始化数据失败！', {
            icon: 5
          })
        })
        .fail(function () {
          layer.msg('初始化数据失败！', {
            icon: 5
          })
        })
        .always(function () {
          layer.close(loading)
        })
    },
    // 获取总行列表
    getHeadBankList: () => (
      new Promise((resolve, reject) => {

        $.ajax({
          url: base + getBank,
          headers: header
        })
          .done(function (res) {
            if (res.code === 0) {
              resolve(res)
            }
            reject(res.message)
          })
          .fail(function () {
            reject()
          })
          .always(function () {
          })

      })
    ),
    // 获取分行列表
    getBranchBankList: function (val) {
      let that           = this,
          defautBankCode = that.defautBankCode;

      $.ajax({
        url: base + getBank,
        headers: header,
        data: {
          bankChannel: val
        }
      })
        .done(function (res) {
          console.log(res);
          that.defautBankCodeList = res;
          that.defautBankCode = defautBankCode;
        })
        .fail(function () {
          layer.msg('初始化数据失败！', {
            icon: 5
          })
        })
        .always(function () {
        })
    },
    // 获取开发商列表
    getDeveloper: () => (
      new Promise((resolve, reject) => {

        $.ajax({
          url: base + getDeveloperList,
          headers: header
        })
          .done(function (res) {
            if (res.code === 0) {
              resolve(res)
            }
            reject(res.message)
          })
          .fail(function () {
            reject()
          })
          .always(function () {
          })

      })
    ),
    // 获取渠道商列表
    getPaychannelList: () => (
      new Promise((resolve, reject) => {

        $.ajax({
          url: base + getPaychannelList,
          headers: header
        })
          .done(function (res) {
            if (res.code === 0) {
              resolve(res)
            }
            reject(res.message)
          })
          .fail(function () {
            reject()
          })
          .always(function () {
          })

      })
    ),
    // 获取服务类型列表
    getServiceTypeList: () => (
      new Promise((resolve, reject) => {

        $.ajax({
          type: 'POST',
          url: base + getServiceType,
          headers: header,
          data: {
            oneServiceType: ''
          }
        })
          .done(function (res) {
            if (res.code === 0) {
              resolve(res)
            }
            reject(res.message)
          })
          .fail(function () {
            console.log("error")
            reject()
          })
          .always(function () {
          })

      })
    ),
    // 获取二类服务类型列表
    getOtherServiceTypeList: (oneServiceType) => {

      let loading = layer.msg('获取数据中...', {
        icon: 16,
        time: 0
      });

      form.otherServiceType     = [];
      form.otherServiceTypeList = [];

      $.ajax({
        type: 'POST',
        url: base + getServiceType,
        headers: header,
        data: {
          oneServiceType: oneServiceType
        }
      })
        .done(function (res) {
          console.log('获取二类服务类型成功！')
          console.log(res)

          if (res.code === 0) {
            form.otherServiceTypeList = res.object;
          }
        })
        .fail(function () {
          console.log("error")

          layer.msg('获取二类服务类型失败...', {
            icon: 5,
            time: 0
          })
        })
        .always(function () {
          layer.close(loading);
        })

    },
    // 获取告知书模版列表
    getInformBookTemplateList: () => (
      new Promise((resolve, reject) => {

        $.ajax({
          url: base + getInformBookTemplateList,
          headers: header
        })
          .done(function (res) {
            if (res.code === 0) {
              resolve(res)
            }
            reject(res.message)
          })
          .fail(function () {
            console.log("error")
            reject()
          })
          .always(function () {
          })

      })
    ),
    // 初始化地图
    initMap: function () {

      let that = this

      let map = new AMap.Map(this.$refs['map-preivew'], {
        resizeEnable: true,
        zoom: 13
      })

      AMap.plugin('AMap.Geocoder', () => {
        let geocoder = new AMap.Geocoder();

        let marker = new AMap.Marker({
          map: map,
          bubble: true
        })

        map.on('click', (e) => {

          marker.setPosition(e.lnglat)

          geocoder.getAddress(e.lnglat, (status, result) => {
            console.log(result)
            console.log(that.province)
            if (status === 'complete') {
              that.propertyAddress = result.regeocode.formattedAddress;
              that.longitude       = e.lnglat.lng;
              that.latitude        = e.lnglat.lat;
            }
          })
        })

      })

    },
    // 初始化时间选择
    initTime: function () {
      let that = this

      $(this.$refs.openQuotationTime)
        .datetimepicker({
          autoclose: true,
          todayBtn: true,
          todayHighlight: true,
          format: "yyyy-mm-dd",
          startView: 3,
          minView: 2
        })
        .on('changeDate', function (e) {

          that.openQuotationTime = $(e.target).val()

        })
    },
    // 锁屏图片上传
    uploadLockImg: function () {

      let that = this,
          file = this.$refs.lockImg.files[0];

      console.log(file);

      if (!file) {
        layer.msg('没有选择文件！', {
          icon: 5
        })

        return
      }

      // 检验文件类型
      let allowExt = ['jpg', 'jpeg', 'png'],
          ext      = file.name.substr(file.name.lastIndexOf('.') + 1);

      if (_.indexOf(allowExt, ext) === -1) {
        layer.msg('文件格式错误,图片格式只能为' + allowExt.toString(), {
          icon: 5
        })

        return
      }

      // 图片大小校验
      let allowWH = new Promise((resolve, reject) => {
        let allowMinWidth  = 1280,
            allowMinHeight = 1080,
            oFReader       = new FileReader();

        oFReader.readAsDataURL(file)

        oFReader.onload = function (e) {
          let img = new Image()

          img.onload = function () {
            console.log()
            if (img.width < allowMinWidth || img.height < allowMinHeight) {
              reject('图片太小了' + (img.width < allowMinWidth ? ',当前图片宽度为' + img.width + 'px, 允许的最小宽度为' + allowMinWidth + 'px' : '') + (img.height < allowMinHeight ? ',当前图片高度为' + img.height + 'px, 允许的最小高度为' + allowMinHeight + 'px' : ''))
            } else {
              resolve()
            }
          }

          img.onerror = function (e) {
            reject('图片加载异常！')
          }

          img.src = e.target.result
        }
      });

      allowWH.then(function () {
        // 文件名称 时间戳 + 6位随机码
        let key = new Date().getTime().toString() + random_string(6) + get_suffix(file.name)

        that.islockImgLock = true;

        let client = new OSS.Wrapper({
          secure: true,
          region: aliyun.region,
          accessKeyId: aliyun.accessKeyId,
          accessKeySecret: aliyun.accessKeySecret,
          bucket: aliyun.bucket
        })

        client.multipartUpload(key, file, {
          progress: function (p) {
            return function (done) {
              that.lockImgProgress = Math.floor(p * 100)
              done()
            }
          }
        }).then(function (res) {
          console.log(res)
          that.lockImg         = key
          that.islockImgLock   = false
          that.lockImgProgress = 0
          that.lockImgPreview  = previewImg(key, {
            'process': 'image/resize,w_350'
          })

          layer.msg('上传锁屏图片成功', {
            icon: 6
          })

        }).catch(function (err) {
          console.log(err)
          that.islockImgLock   = false
          that.lockImgProgress = 0

          layer.msg('上传锁屏图片失败', {
            icon: 5
          })

        })
      }).catch(function (error) {
        layer.msg(error || '图片异常', {
          icon: 5,
          time: 8000
        })
      })

    },
    imgPreviewModal: imgPreviewModal,
    clearImgPreview: function (e) {
      this.lockImgPreview    = '';
      this.lockImg           = '';
      this.$refs.lockImg.val = '';
    },
    resetManager: function () {
      let loading = layer.msg('重置中...', {
        icon: 16,
        time: 0
      });

      $.ajax({
        type: 'POST',
        url: base + resetAdminNo,
        headers: header,
        data:{
          userName: this.adminNo
        }
      })
        .done(function (res) {
          if (res.code !== 0) {
            layer.msg('重置管理员账号失败！', {
              icon: 5
            })
            return
          }

          layer.msg('重置管理员账号成功，初始密码为 123456！', {
            icon: 6
          })

          form.adminName = ''
          form.adminPhone = ''
        })
        .fail(function () {
          layer.msg('重置管理员账号失败！', {
            icon: 5
          })
        })
        .always(function () {
          layer.close(loading);
        })
    }
  }
})

function valid () {

  let form_valid,
      $form = $('#form')

  $.validator.setDefaults({ // 只能放在validate规则配置之前

    // 提交事件
    submitHandler: () => {
      console.log('submit!')

      let loading_modal = layer.msg('提交中...', {
        icon: 16,
        time: 0
      })

      form.isLock = true

      $.ajax({
        url: base + addOrModifyBuildinginfo,
        type: 'POST',
        headers: header,
        contentType: 'application/json',
        data: JSON.stringify(
          {
            buildingInfo: {
              // 总行
              channel: form.rootBank,
              // 分行
              defautBankCode: form.defautBankCode,
              id: form.id,
              // 楼盘名称
              propertyName: form.propertyName,
              // 楼盘地址
              propertyAddress: form.propertyAddress,
              // 楼盘区域
              propertyArea: form.propertyArea,
              // 省code
              province: form.province,
              // 市code
              city: form.city,
              // 开盘时间
              openQuotationTime: form.openQuotationTime,
              // 开发商ID
              dId: form.dId,
              // 负责人联系方式
              picMobile: form.picMobile,
              // 负责人姓名
              picName: form.picName,
              // 是否创建测试户型
              isCreateTestType: form.isCreateTestType,
              // 售房电话（多个用逗号隔开）
              salePhone: form.salePhone,
              // 管理者账号
              adminNo: form.adminNo,
              // 开发商名称
              developerName: _.find(form.developerList, (item) => (item.idStr === form.dId)).enterInfo.enterpriseName,
              /*// 是否全民经纪人可看
               broker: form.broker,
               // 是否查询真信报告
               isCheckZxbg: form.isCheckZxbg,
               // 是否付款给开发商
               isPayToDev: form.isPayToDev,
               // 是否锁屏
               isLock: form.isQuickLock,
               // 是否POS小票签名
               posSignature: form.posSignature,
               // 是否显示楼盘名称
               isShowName: form.isShowName,
               // 是否显示银行相关信息
               showBankInfo: form.showBankInfo,
               // 是否显示认购协议
               agreement: form.serviceType === 'xf' ? form.agreement : undefined,
               // 是否在公众号展示
               isView: form.isView,
               // 是否签名
               isSignature: form.isSignature,
               // 独立经纪人佣金模式
               brokerCommModel: form.brokerCommModel,
               // 独立经纪人佣金配置
               brokerCommConfig: form.brokerCommConfig,
               // 职业顾问佣金模式
               careerCounselorModel: form.careerCounselorModel,
               // 职业顾问佣金配置
               careerCounselorConfig: form.careerCounselorConfig,
               // 是否切换Pos
               changePosPay: form.changePosPay,
               // 锁屏图片OSS
               lockImg: form.lockImg,
               // 锁定时间
               lockTime: form.lockTime,
               // 经度
               longitude: form.longitude,
               // 纬度
               latitude: form.latitude,
               // 告知书打印次数
               printNum: form.printNum,
               // 银联小票打印次数
               ylTicketCount: form.ylTicketCount,
               // 服务类型
               serviceType: form.serviceType,
               // 其它服务类型
               otherServiceType: form.otherServiceType.join(','),
               // 告知书模板id
               templetId: form.templetId,
               // 是否显示退款业务
               cancelDeposit: form.cancelDeposit,
               // 退款通知手机
               refundReceiveSMSPhone: form.refundReceiveSMSPhone,
               orderOverdueTime: form.orderOverdueTime,
               overdueTime: form.overdueTime,*/
            },
            buildingInfoFileModel: {}
          })
      })
        .done(function (res) {
          console.log(res);

          if (res.code === -1) {
            layer.msg(res.message, {
              icon: 5
            })

            form.isLock = false

            return
          }

          layer.msg(`${ action }${ title }成功`, {
            icon: 6
          })

          // 重置表单
          $.extend(form.$data, form.$options.data());

          setTimeout(() => {
            window.location = './index.html'
          }, 1000)
        })
        .fail(function (res) {
          console.log(res)

          layer.msg(`${ action }${ title }失败`, {
            icon: 5
          })

          console.log("error");
        })
        .always(function (res) {

          layer.close(loading_modal)
          form.isLock = false

        })

    }
  });

  // 验证
  form_valid = $form.validate({
    errorPlacement: function (error, element) {
      element.parents('.col-sm-12').length ? error.appendTo(element.parents('.col-sm-12')) : error.appendTo(element.parents('.col-xs-24'))
    },
    rules: {
      picName: valid_name,
      adminNo: valid_checkManagerNo,
      propertyName: {
        required: true
      },
      dId: {
        required: true
      },
      propertyArea: {
        required: true
      },
      province: {
        required: true
      },
      city: {
        required: true
      },
      propertyAddress: {
        required: true
      },
      rootBank: {
        required: true
      },
      defautBankCode: {
        required: true
      },
      picMobile: {
        required: true,
        phone: true
      },
      openQuotationTime: {
        required: true
      },
      serviceType: {
        required: true
      },
      isCreateTestType: {
        required: true
      },
      // longitude: {
      // required: true
      // },
      // latitude: {
      // required: true
      // },
      // channel: {
      // required: true
      // },
      // broker: {
      // required: true
      // },
      // isShowName: {
      //   required: true
      // },
      // showBankInfo: {
      //   required: true
      // },
      // isCheckZxbg: {
      //  required: true
      // },
      // isPayToDev: {
      //  required: true
      // },
      // careerCounselorModel: {
      // required: true
      // },
      // careerCounselorConfig: valid_price,
      // brokerCommModel: {
      // required: true
      // },
      // brokerCommConfig: valid_price,
      // isView: {
      // required: true
      // },
      // posSignature: {
      //   required: true
      // },
      // printNum: {
      //   required: true
      // },
      // ylTicketCount: {
      //   required: true
      // },
      // lockTime: {
      //   required: true
      // },
      // lockImg: valid_checkImg,
      // cancelDeposit: {
      //   required: true
      // },
      // orderOverdueTime: {
      //   digits: true
      // },
      // overdueTime: {
      //   digits: true
      // },
    }
  })

}